package com.osp.Graph;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.swing.JFrame;

import com.osp.model.Employee;
import com.osp.model.Task;

import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.graphics.DrawingContext;
import de.erichseifert.gral.io.plots.DrawableWriter;
import de.erichseifert.gral.io.plots.DrawableWriterFactory;
import de.erichseifert.gral.plots.PiePlot;
import de.erichseifert.gral.plots.PiePlot.PieSliceRenderer;
import de.erichseifert.gral.plots.colors.LinearGradient;
import de.erichseifert.gral.ui.InteractivePanel;
import de.erichseifert.gral.util.Insets2D;

public class DataPlot extends ExamplePanel {
	private Employee empToShow = null;
	private PiePlot plot = null;
	private DataTable data = new DataTable(Float.class);

	private static final int SAMPLE_COUNT = 10;
	/** Instance to generate random data values. */
	private static Random random = new Random();

	@SuppressWarnings("unchecked")
	public DataPlot( Employee employeeToShow) {
		// Create data

		DataTable data = PrepareDataToPlot(employeeToShow);
		
		plot = new PiePlot(data);
		plot.getTitle().setText(getDescription());
		plot.setRadius(0.9);
		plot.setLegendVisible(true);
		plot.setInsets(new Insets2D.Double(20.0, 40.0, 40.0, 40.0));

		PieSliceRenderer pointRenderer = (PieSliceRenderer) plot.getPointRenderer(data);
		pointRenderer.setInnerRadius(0.4);
		pointRenderer.setGap(0.2);
		LinearGradient colors = new LinearGradient(COLOR1, COLOR2);
		pointRenderer.setColor(colors);
		pointRenderer.setValueVisible(true);
		pointRenderer.setValueColor(Color.WHITE);
		pointRenderer.setValueFont(Font.decode(null).deriveFont(Font.BOLD));

		// Add plot to Swing component
		add(new InteractivePanel(plot), BorderLayout.CENTER);
	}
	
	public DataTable PrepareDataToPlot(Employee employee)
	{
		Map<Integer,Integer> projectData = new HashMap<Integer,Integer>();
		List<String> projects = new ArrayList<String>();
		int time = 0;
		
		if (employee != null)
		{
			for (Integer year : employee.getTasks().keySet()) {
				for (Task task : employee.getTasks().get(year)) {

					if (!projects.contains(task.getProjectName()))
					{
						projects.add(task.getProjectName());
						projectData.put(projects.size(), task.getElapsedMinutes());
						time +=task.getElapsedMinutes();
					}
					else
					{
						int projID = ProjectID(task.getProjectName(), projects)+1;
						projectData.put(projID, projectData.get(projID)+task.getElapsedMinutes());
						time +=task.getElapsedMinutes();
					}
				}
			}					
			
			for (Integer temp : projectData.keySet()) {
				data.add((projectData.get(temp)*100.0f/time));
			}	
		}
		return data;
		
	}
	
	public int ProjectID(String projectName,List<String> projects)
	{
		for (int i = 0; i<projects.size(); i++)
		{
			if (projects.get(i).equals(projectName))
				return i;
		}
		
		return -1;
	}

	@Override
	public String getTitle() {
		if (empToShow!=null)
			return "Wykres";	
		return "";
	}

	@Override
	public String getDescription() {
		if (empToShow!=null)
			return "Raport procentowego zestawienia projektow dla " +empToShow.getName();
		return "";
	}
	
	/**
	 * Opens a frame and shows the example in it.
	 * @return the frame instance used for displaying the example.
	 */
	protected JFrame showInFrame() {
		JFrame frame = new JFrame(getTitle());
		frame.getContentPane().add(this, BorderLayout.CENTER);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(getPreferredSize());
		frame.setVisible(true);
		return frame;
	}
	
	public byte[] getJpg() throws IOException {
        BufferedImage bImage = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = (Graphics2D) bImage.getGraphics();
        DrawingContext context = new DrawingContext(g2d);
        plot.draw(context);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DrawableWriter wr = DrawableWriterFactory.getInstance().get("image/jpeg");
        wr.write(plot, baos, 800, 600);
        baos.flush();
        byte[] bytes = baos.toByteArray();
        baos.close();
        return bytes;
    }
}
